#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<sys/wait.h>
#include<string.h>
#include<sys/types.h>

int main(int argc, char const *argv[]) {
    char share_name[100] = {0};
    sprintf(share_name, "test1");
    

    // 申请共享内存对象
    int fd = shm_open(share_name, O_RDWR | O_CREAT, 0644);
    if (fd == -1) {
        perror("shm_open");
        exit(EXIT_FAILURE);
    }

    
    // 设置共享内存大小
    if (ftruncate(fd, 1024) == -1) {
        perror("ftruncate");
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 映射共享内存
    char *addr = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr == MAP_FAILED) {
        perror("mmap");
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 写入共享内存
    pid_t pid=fork();
    if (pid==0)
    {
        //子进程的代码,子进程写入数据
        sprintf(addr,"对不起，你是一个好人%d",getppid());
        exit(EXIT_SUCCESS);
    }else if (pid>0)
    {   
        sleep(1);
        //父进程的代码
        printf("%s",addr);
        
    }else
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    

    
    

    // 关闭文件描述符
    close(fd);

    // 关闭映射共享内存
    if (munmap(addr, 1024) == -1) {
        perror("munmap");
        exit(EXIT_FAILURE);
    }

    // 释放共享内存对象
    if (shm_unlink(share_name) == -1) {
        perror("shm_unlink");
        exit(EXIT_FAILURE);
    }

    return 0;
}
